package org.wanho.txy.ems.controller;

import com.alibaba.fastjson.JSON;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.wanho.txy.ems.vo.ResponseResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;

/**
 * Author：汤小洋
 * Date：2023-05-11 19:33
 * Description：<描述>
 */
@WebServlet("/upload")
public class UploadController  extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List<FileItem> items = upload.parseRequest(req);
            for(FileItem item : items){
                // 判断是普通文本还是文件
                if (item.isFormField()){ // 普通文本
                    System.out.println("参数名："+item.getFieldName());
                    System.out.println("参数值："+item.getString());
                }else{ // 文件
                    System.out.println("文件名：" +item.getName());
                    System.out.println("文件大小：" + item.getSize());
                    System.out.println("文件类型：" +item.getContentType());
                    System.out.println("文件内容：" + item.getInputStream());

                    // 为文件重命名，确保文件名唯一
                    String fileName = UUID.randomUUID().toString() + item.getName().substring(item.getName().lastIndexOf("."));
                    // 获取upload目录的物理路径(idea部署项目时，默认不会发布空目录)
                    String pathName =  req.getServletContext().getRealPath("/upload/imgs") + File.separator + fileName;
                    System.out.println(pathName);
                    // 保存文件
                    item.write(new File(pathName));

                    resp.setContentType("application/json;charset=utf8");
                    PrintWriter out = resp.getWriter();
                    out.print(JSON.toJSONString(ResponseResult.success("/upload/imgs/" + fileName)));
                    out.close();
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
